package org.jeecg.modules.yinsheng;

import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.yinsheng.command.base.BaseBizReqCommand;
import org.jeecg.modules.yinsheng.command.base.BaseHeadReqCommand;
import org.jeecg.modules.yinsheng.command.base.HeadResponseCommand;
import org.jeecg.modules.yinsheng.common.ServiceEnum;
import org.jeecg.modules.yinsheng.common.YsPayConstant;
import org.jeecg.modules.yinsheng.utils.HttpClient;
import org.jeecg.modules.yinsheng.utils.JsonParser;
import org.jeecg.modules.yinsheng.utils.SignUtils;
import org.jeecg.modules.yinsheng.utils.StringUtils;
import org.jeecg.modules.yinsheng.utils.ValidateUtils;
import org.jeecg.modules.yinsheng.utils.YinshengLogger;
import org.jeecg.modules.yinsheng.utils.YsChannelClientException;
import org.jeecg.modules.yinsheng.utils.YsChannelEnum;
import org.jeecg.modules.yinsheng.utils.YsMpPayUtils;

/**
 * @Description 客户端
 * @Author linxl
 * @Date 2021/4/1 9:18
 * @Version 1.0
 */
@Slf4j
public class YinShengClient {

	/**
	 * 接口名称
	 */
	private String api;
	/**
	 * 环境
	 */
	private String env;

	private String url;
	/**
	 * 证书路径
	 */
	private String privateCerPath;

	/**
	 * 私钥证书密码
	 */
	private String privateCerPwd;

	private ServiceEnum serviceEnum;

	private String rsaPrd;

	/**
	 * 交易
	 * 
	 * @param
	 * @param bizReq bizReqJson 业务参数
	 * @return
	 */
	public HeadResponseCommand doAction(BaseHeadReqCommand baseReqCommand, BaseBizReqCommand bizReq) {

		try {
			ValidateUtils.validate(bizReq);
			return requestApi(baseReqCommand, JsonParser.toJson(bizReq));
		} catch (Exception e) {
			YinshengLogger.logBizError(e);
			return exceptionHandle(e);
		}
	}

	/**
	 * 
	 * <p>基本请求</p>
	 * 
	 * @user zcw 2021年6月21日 下午5:25:07
	 */
	public HeadResponseCommand baseAction(BaseHeadReqCommand baseReqCommand, Object bizReq) {
		try {
			ValidateUtils.validate(bizReq);
			return requestApi(baseReqCommand, JsonParser.toJson(bizReq));
		} catch (Exception e) {
			YinshengLogger.logBizError(e);
			return exceptionHandle(e);
		}
	}

	/**
	 * 
	 * <p>接口请求</p>
	 * 
	 * @user zcw 2021年6月21日 下午5:24:41
	 */
	public HeadResponseCommand requestApi(BaseHeadReqCommand baseReqCommand, String bizReq) {

		long startTime = System.currentTimeMillis();
		try {
			ValidateUtils.validate(baseReqCommand);
			baseReqCommand.setBizReqJson(bizReq);

			Map<String, String> buildResponseSign = YsMpPayUtils.buildResponseSign(privateCerPwd, privateCerPath,
					baseReqCommand);

			log.info("银盛渠道发起数据[" + buildResponseSign.toString() + "]");
			String result = HttpClient.post(url, buildResponseSign);
			if (StringUtils.isBlank(result)) {
				 log.info("银盛渠道返回数据为空");
				throw new YsChannelClientException(YsChannelEnum.CHANNEL_NULL_MSG_FAIL.getCode(),
						YsChannelEnum.CHANNEL_NULL_MSG_FAIL.getMessage());
			}
			 log.info("银盛渠道返回数据[" + result + "]");
			JSONObject o = JSONObject.parseObject(result, Feature.OrderedField);
			Map map = JSON.parseObject(JSONObject.toJSONString(o, SerializerFeature.WriteMapNullValue),
					Feature.OrderedField);
			String bizResponseJson = null;
			if (null != map.get("bizResponseJson")) {
				bizResponseJson = JSONObject.toJSONString(map.get("bizResponseJson"),
						SerializerFeature.WriteMapNullValue, SerializerFeature.SortField);
				map.put("bizResponseJson", bizResponseJson);
			}
			HeadResponseCommand headResponseCommand = JsonParser.parse(result, HeadResponseCommand.class);
			headResponseCommand.setBizResponseJson(bizResponseJson);
			if (!YsMpPayUtils.verifySign(map, rsaPrd)) {
				return new HeadResponseCommand(YsChannelEnum.STATUS_FAIL.getMessage(),
						YsChannelEnum.VERIFY_SIGN_FAIL.getMessage());
			}
			long endTime = System.currentTimeMillis();
			 log.info("接口请求总耗时[" + (endTime - startTime) + "]ms");
			return headResponseCommand;
		} catch (Exception e) {
			 log.info("银盛渠道返回数据sdk解析出错");
			YinshengLogger.logBizError(e);
			return exceptionHandle(e);
		}
	}

	// 统一异常处理
	public HeadResponseCommand exceptionHandle(Exception e) {
		if (e instanceof YsChannelClientException) {
			YsChannelClientException ysChannelClientException = (YsChannelClientException) e;
			return new HeadResponseCommand(ysChannelClientException.getCode(), ysChannelClientException.getMessage());
		}
		return new HeadResponseCommand(YsChannelEnum.REQ_IO_EXCEPTION_2_FAIL.getCode(),
				YsChannelEnum.REQ_IO_EXCEPTION_2_FAIL.getMessage());

	}

	public YinShengClient(ServiceEnum serviceEnum, String env, String privateCerPath, String privateCerPwd,String rsaPrd) {
		this.serviceEnum = serviceEnum;
		this.api = serviceEnum.getApiName();
		this.privateCerPath = privateCerPath;
		this.privateCerPwd = privateCerPwd;
		this.rsaPrd = rsaPrd;
		this.env = env;
		this.url = serviceEnum.getTestUrl();
		if (YsPayConstant.ENV_PRD.equals(env)) {
			this.url = serviceEnum.getPrdUrl();
		}
	}
}
